package com.txzhang.springcloud.goodserver.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.txzhang.springcloud.goodserver.entity.Good;
import com.txzhang.springcloud.goodserver.mapper.GoodMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;

@Slf4j
@Service
public class GoodService extends ServiceImpl<GoodMapper, Good> {

    public void reduceGood(@NotNull String goodCode, Integer count) {
        QueryWrapper<Good> query = new QueryWrapper<>();
        query.eq("code", goodCode);
        Good good = baseMapper.selectOne(query);
        if (good == null) {
            log.error("不存在该商品{}", goodCode);
        }
        if (good.getCount() < count) {
            log.error("库存不足，剩余{}， 要购买{}", good.getCount(), count);
            throw new RuntimeException("库存不足");
        }
        good.setCount(good.getCount() - count);
        baseMapper.updateById(good);
    }
}
